# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import SUPERUSER_ID
from openerp.tools.safe_eval import safe_eval as eval

class sale_gross_profit_recompute(osv.osv):
    _name = 'sale.gross.profit.recompute'
    _columns = {
         'all_num': fields.integer(string='选中销售订单数', readonly=True),
         'check_out_num': fields.integer(string='重算订单数', readonly=True),
         'sale_order_string': fields.char(string='合格的销售订单', readonly=True),
         'sale_order_ids_string': fields.char(string='合格的销售订单', readonly=True),
    }

    def get_select_sale_message(self, cr, uid, context=None):
        check_out_num_list = []
        for sale_order_row in self.pool.get('sale.order').browse(cr,
                                        uid, context.get('active_ids'),context=context):
            if all([line.is_gross_profit_checked for line in sale_order_row.order_line]):
                check_out_num_list.append(sale_order_row.id)
        return len(check_out_num_list)

    def get_select_sale_message_string(self, cr, uid, context=None):
        sale_order_string_list = []
        check_out_num_list = []
        for sale_order_row in self.pool.get('sale.order').browse(cr,
                                        uid, context.get('active_ids'),context=context):
            if all([line.is_gross_profit_checked for line in sale_order_row.order_line]):
                sale_order_string_list.append(sale_order_row.name)
                check_out_num_list.append(sale_order_row.id)
        return str(check_out_num_list)

    def confirm_recompute(self, cr, uid, ids, context=None):
        for recompute_row in self.browse(cr, uid, ids, context=context):
            sale_order_line_ids = []
            for sale_order_row in  self.pool.get('sale.order').browse(cr, uid,
                                eval(recompute_row.sale_order_ids_string),context=context):
                [sale_order_line_ids.append(line.id) for line in sale_order_row.order_line]
            self.pool.get('sale.order.line').gross_profit_rate_type(cr, uid, sale_order_line_ids,
                                                                    context=context)
        return True

    _defaults = {
        'all_num': lambda s, c, u, context={}:len(context.get('active_ids')),
        'check_out_num': get_select_sale_message,
        'sale_order_ids_string': get_select_sale_message_string,
    }